package com.gao.web.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author gao
 * @time 2020/07/03 14:17:02
 */
@Controller
@RequestMapping("auth")
public class AuthController {
    @PostMapping("login")
    public String login(String username, String password) {

        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        String path = "";
        try {
            subject.login(token);
            path = "home";
        } catch (AuthenticationException e) {
            e.printStackTrace();
            path = "index";
        }

        return "redirect:/" + path + ".jsp";
    }

//    @GetMapping("logout")
//    public String logout() {
//        Subject subject = SecurityUtils.getSubject();
//        subject.logout();
//        return "redirect:/index.jsp";
//    }


    @RequiresAuthentication
    @RequiresRoles("admin")
    @RequestMapping("f1")
    public String f1() {
        System.out.println("f1");
        return "home";
    }

    @RequiresAuthentication
    @RequiresRoles("guest")
    @RequestMapping("f2")
    public String f2() {
        System.out.println("f2");
        return "home";
    }

}
